export class GameScene extends Phaser.Scene {
    constructor() {
        super({ key: 'GameScene' });
        this.cards = [];
        this.enemies = [];
        this.playerEnergy = 3;
        this.playerHealth = 80;
        this.maxPlayerHealth = 80;
        this.enemyHealth = 40;
        this.maxEnemyHealth = 40;
        this.turn = 'player';
    }

    create() {
        // 添加背景
        this.add.rectangle(0, 0, this.game.config.width, this.game.config.height, 0x0a0a1a)
            .setOrigin(0);

        // 创建界面元素
        this.createUI();
        
        // 创建敌人
        this.createEnemy();
        
        // 创建玩家
        this.createPlayer();
        
        // 创建卡牌
        this.createInitialDeck();
        
        // 抽牌
        this.drawCards(5);
        
        // 添加回合结束按钮
        this.createEndTurnButton();
    }

    createUI() {
        // 玩家状态区
        this.playerHealthText = this.add.text(100, 50, `生命: ${this.playerHealth}/${this.maxPlayerHealth}`, {
            fontSize: '24px',
            fill: '#ffffff'
        });
        
        this.playerEnergyText = this.add.text(100, 90, `能量: ${this.playerEnergy}`, {
            fontSize: '24px',
            fill: '#ffffff'
        });
        
        // 敌人状态区
        this.enemyHealthText = this.add.text(this.game.config.width - 250, 50, `敌人生命: ${this.enemyHealth}/${this.maxEnemyHealth}`, {
            fontSize: '24px',
            fill: '#ffffff'
        });
        
        // 敌人意图
        this.enemyIntentText = this.add.text(this.game.config.width - 250, 90, '意图: 攻击 12', {
            fontSize: '24px',
            fill: '#ff0000'
        });
    }

    createEnemy() {
        // 创建简单敌人
        const enemy = this.add.rectangle(this.game.config.width - 200, 250, 100, 150, 0xff0000);
        this.enemies.push(enemy);
    }

    createPlayer() {
        // 创建玩家角色
        this.player = this.add.rectangle(200, 400, 100, 150, 0x0000ff);
    }

    createInitialDeck() {
        // 创建初始卡组
        const cardTypes = [
            { name: '小波', type: 'attack', cost: 1, damage: 6 },
            { name: '中波', type: 'attack', cost: 2, damage: 10 },
            { name: '大波', type: 'attack', cost: 3, damage: 15 },
            { name: '防御', type: 'skill', cost: 1, block: 5 },
            { name: '强化', type: 'power', cost: 1, effect: 'strength' },
            { name: '张永爪', type: 'attack', cost: 2, damage: 11 },
            { name: '冬瓜重拳', type: 'attack', cost: 1, damage: 8, selfDamage: 3 }
        ];
        
        // 添加初始卡牌到牌库
        for (let i = 0; i < 10; i++) {
            const cardType = cardTypes[i % cardTypes.length];
            window.gameState.deck.push({ ...cardType });
        }
        
        // 洗牌
        this.shuffleDeck();
    }

    shuffleDeck() {
        // 简单洗牌算法
        for (let i = window.gameState.deck.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [window.gameState.deck[i], window.gameState.deck[j]] = [window.gameState.deck[j], window.gameState.deck[i]];
        }
    }

    drawCards(count) {
        // 抽牌
        for (let i = 0; i < count; i++) {
            if (window.gameState.deck.length === 0) {
                // 如果牌库空了，将弃牌堆洗回牌库
                window.gameState.deck = [...window.gameState.discardPile];
                window.gameState.discardPile = [];
                this.shuffleDeck();
            }
            
            if (window.gameState.deck.length > 0) {
                const card = window.gameState.deck.pop();
                window.gameState.hand.push(card);
                this.createCardInHand(card, window.gameState.hand.length - 1);
            }
        }
    }

    createCardInHand(card, index) {
        // 创建卡牌UI
        const cardWidth = 120;
        const cardHeight = 160;
        const cardSpacing = 130;
        const startX = this.game.config.width / 2 - ((window.gameState.hand.length - 1) * cardSpacing) / 2;
        const y = this.game.config.height - 100;
        
        // 创建卡牌背景
        const cardBg = this.add.rectangle(startX + index * cardSpacing, y, cardWidth, cardHeight, 0x333333);
        cardBg.setStrokeStyle(2, 0xffffff);
        
        // 卡牌名称
        const nameText = this.add.text(startX + index * cardSpacing, y - 50, card.name, {
            fontSize: '16px',
            fill: '#ffffff'
        }).setOrigin(0.5);
        
        // 卡牌费用
        const costText = this.add.text(startX + index * cardSpacing - 50, y - 70, card.cost.toString(), {
            fontSize: '24px',
            fill: '#00ffff'
        }).setOrigin(0.5);
        
        // 卡牌描述
        let description = '';
        if (card.type === 'attack') {
            if (card.name === '冬瓜重拳' && card.selfDamage) {
                description = `造成 ${card.damage} 点伤害，自己失去 ${card.selfDamage} 点生命`;
            } else {
                description = `造成 ${card.damage} 点伤害`;
            }
        } else if (card.type === 'skill') {
            description = `获得 ${card.block} 点格挡`;
        } else if (card.type === 'power') {
            description = '增加1点力量';
        }
        
        const descText = this.add.text(startX + index * cardSpacing, y + 20, description, {
            fontSize: '14px',
            fill: '#ffffff',
            wordWrap: { width: cardWidth - 10 }
        }).setOrigin(0.5);
        
        // 组合卡牌对象
        const cardObj = {
            bg: cardBg,
            nameText,
            costText,
            descText,
            data: card
        };
        
        // 添加交互
        cardBg.setInteractive();
        cardBg.on('pointerover', () => {
            cardBg.y -= 20;
            nameText.y -= 20;
            costText.y -= 20;
            descText.y -= 20;
        });
        
        cardBg.on('pointerout', () => {
            cardBg.y += 20;
            nameText.y += 20;
            costText.y += 20;
            descText.y += 20;
        });
        
        cardBg.on('pointerdown', () => {
            this.playCard(cardObj, index);
        });
        
        this.cards.push(cardObj);
    }

    playCard(cardObj, index) {
        const card = cardObj.data;
        
        // 检查能量是否足够
        if (this.playerEnergy < card.cost) {
            // 能量不足，卡牌抖动效果
            this.tweens.add({
                targets: [cardObj.bg, cardObj.nameText, cardObj.costText, cardObj.descText],
                x: '+=10',
                duration: 50,
                yoyo: true,
                repeat: 3
            });
            return;
        }
        
        // 使用卡牌
        this.playerEnergy -= card.cost;
        this.playerEnergyText.setText(`能量: ${this.playerEnergy}`);
        
        // 卡牌效果
        if (card.type === 'attack') {
            // 攻击动画
            this.tweens.add({
                targets: this.player,
                x: 400,
                duration: 200,
                yoyo: true,
                onComplete: () => {
                    // 造成伤害
                    this.enemyHealth -= card.damage;
                    if (this.enemyHealth < 0) this.enemyHealth = 0;
                    this.enemyHealthText.setText(`敌人生命: ${this.enemyHealth}/${this.maxEnemyHealth}`);
                    
                    // 冬瓜重拳特殊效果：自己生命-3
                    if (card.name === '冬瓜重拳' && card.selfDamage) {
                        this.playerHealth -= card.selfDamage;
                        if (this.playerHealth < 0) this.playerHealth = 0;
                        this.playerHealthText.setText(`生命: ${this.playerHealth}/${this.maxPlayerHealth}`);
                    }
                    // 检查敌人是否死亡
                    if (this.enemyHealth <= 0) {
                        this.enemyDefeated();
                    }
                }
            });
        } else if (card.type === 'skill') {
            // 获得格挡
            // 这里简化处理，直接增加生命值
            this.playerHealth += card.block;
            if (this.playerHealth > this.maxPlayerHealth) this.playerHealth = this.maxPlayerHealth;
            this.playerHealthText.setText(`生命: ${this.playerHealth}/${this.maxPlayerHealth}`);
        } else if (card.type === 'power') {
            // 增加力量效果
            // 这里简化处理，显示一个提示
            const powerText = this.add.text(this.player.x, this.player.y - 50, '+1 力量', {
                fontSize: '24px',
                fill: '#ffff00'
            }).setOrigin(0.5);
            
            this.tweens.add({
                targets: powerText,
                y: this.player.y - 100,
                alpha: 0,
                duration: 1000,
                onComplete: () => powerText.destroy()
            });
        }
        
        // 从手牌移除
        window.gameState.hand.splice(index, 1);
        window.gameState.discardPile.push(card);
        
        // 移除卡牌UI
        cardObj.bg.destroy();
        cardObj.nameText.destroy();
        cardObj.costText.destroy();
        cardObj.descText.destroy();
        this.cards.splice(index, 1);
        
        // 重新排列手牌
        this.rearrangeHand();
    }

    rearrangeHand() {
        const cardSpacing = 130;
        const startX = this.game.config.width / 2 - ((window.gameState.hand.length - 1) * cardSpacing) / 2;
        const y = this.game.config.height - 100;
        
        for (let i = 0; i < this.cards.length; i++) {
            const card = this.cards[i];
            card.bg.x = startX + i * cardSpacing;
            card.nameText.x = startX + i * cardSpacing;
            card.costText.x = startX + i * cardSpacing - 50;
            card.descText.x = startX + i * cardSpacing;
        }
    }

    createEndTurnButton() {
        const button = this.add.rectangle(this.game.config.width - 150, this.game.config.height - 50, 200, 60, 0x444444)
            .setInteractive();
        
        const buttonText = this.add.text(this.game.config.width - 150, this.game.config.height - 50, '结束回合', {
            fontSize: '24px',
            fill: '#ffffff'
        }).setOrigin(0.5);
        
        button.on('pointerover', () => {
            button.fillColor = 0x666666;
        });
        
        button.on('pointerout', () => {
            button.fillColor = 0x444444;
        });
        
        button.on('pointerdown', () => {
            this.endPlayerTurn();
        });
    }

    endPlayerTurn() {
        // 清空手牌
        for (const card of this.cards) {
            card.bg.destroy();
            card.nameText.destroy();
            card.costText.destroy();
            card.descText.destroy();
            window.gameState.discardPile.push(card.data);
        }
        
        window.gameState.hand = [];
        this.cards = [];
        
        // 开始敌人回合
        this.turn = 'enemy';
        this.enemyTurn();
    }

    enemyTurn() {
        // 敌人行动
        const damage = 12; // 简化处理，固定伤害
        
        // 显示敌人攻击动画
        this.tweens.add({
            targets: this.enemies[0],
            x: 400,
            duration: 200,
            yoyo: true,
            onComplete: () => {
                // 造成伤害
                this.playerHealth -= damage;
                if (this.playerHealth < 0) this.playerHealth = 0;
                this.playerHealthText.setText(`生命: ${this.playerHealth}/${this.maxPlayerHealth}`);
                
                // 检查玩家是否死亡
                if (this.playerHealth <= 0) {
                    this.gameOver();
                } else {
                    // 开始新的玩家回合
                    this.startNewTurn();
                }
            }
        });
    }

    startNewTurn() {
        // 重置能量
        this.playerEnergy = 3;
        this.playerEnergyText.setText(`能量: ${this.playerEnergy}`);
        
        // 抽新卡
        this.drawCards(5);
        
        // 更新敌人意图
        this.enemyIntentText.setText('意图: 攻击 12');
        
        // 设置为玩家回合
        this.turn = 'player';
    }

    enemyDefeated() {
        // 显示胜利信息
        const victoryText = this.add.text(this.game.config.width / 2, this.game.config.height / 2, '胜利！', {
            fontSize: '64px',
            fill: '#ffff00'
        }).setOrigin(0.5);
        
        // 添加返回主菜单按钮
        const menuButton = this.add.text(this.game.config.width / 2, this.game.config.height / 2 + 100, '返回主菜单', {
            fontSize: '32px',
            fill: '#ffffff'
        })
        .setOrigin(0.5)
        .setInteractive();
        
        menuButton.on('pointerover', () => {
            menuButton.setStyle({ fill: '#ff0' });
        });
        
        menuButton.on('pointerout', () => {
            menuButton.setStyle({ fill: '#ffffff' });
        });
        
        menuButton.on('pointerdown', () => {
            this.scene.start('MainMenuScene');
        });
    }

    gameOver() {
        // 显示失败信息
        const gameOverText = this.add.text(this.game.config.width / 2, this.game.config.height / 2, '游戏结束', {
            fontSize: '64px',
            fill: '#ff0000'
        }).setOrigin(0.5);
        
        // 添加返回主菜单按钮
        const menuButton = this.add.text(this.game.config.width / 2, this.game.config.height / 2 + 100, '返回主菜单', {
            fontSize: '32px',
            fill: '#ffffff'
        })
        .setOrigin(0.5)
        .setInteractive();
        
        menuButton.on('pointerover', () => {
            menuButton.setStyle({ fill: '#ff0' });
        });
        
        menuButton.on('pointerout', () => {
            menuButton.setStyle({ fill: '#ffffff' });
        });
        
        menuButton.on('pointerdown', () => {
            this.scene.start('MainMenuScene');
        });
    }
}